/**
 * @author 紫伟宸
 * @time 2009-7-17 上午09:39:26
 */
package org.yoao.crm.business.impl;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.yoao.crm.bean.Customer;
import org.yoao.crm.bean.CustomerAttributes;
import org.yoao.crm.bean.Session;
import org.yoao.crm.bean.StaticBean;
import org.yoao.crm.business.service.IExportService;
import org.yoao.crm.dao.CustomerAttributesDAO;
import org.yoao.crm.dao.CustomerDAO;
import org.yoao.crm.dao.ExportDAO;
import org.yoao.crm.tools.CodeFactory;
import org.yoao.crm.tools.ExcelTool;

/**
 * @author 紫伟宸 导入导出
 * @time 2009-7-17 上午09:39:26
 */
public class ExportServiceImpl implements IExportService {
	private static final Logger log = Logger.getLogger(ExportServiceImpl.class);
	private CustomerDAO customerDAO = new CustomerDAO();
	private CustomerAttributesDAO customerAttributesDAO = new CustomerAttributesDAO();
	private ExportDAO exportDAO = new ExportDAO();
	private ExcelTool excelTool = new ExcelTool();
	private static final String[] title = { "CUSTOMERID", "CUSTOMERNAME",
			"COMPANYNAME", "PROVINCE", "CITY", "PHONE", "MOBILE", "QQ",
			"EMAIL", "BIRTHDAY", "STATE", "SIGNATURE", "SIGNTIME", "AMOUNT",
			"PAYTIME", "USERSNO", "ROLEID", "MEMO" };

	/***
	 * 导入
	 */
	public String exportIn(String filePath, Session session) throws Exception {
		StringBuffer result = new StringBuffer();
		int count = 0;
		excelTool.setFilePath(filePath);
		List data = excelTool.read(title);
		if (data != null && !data.isEmpty()) {
			int size = data.size();
			count = size;
			for (int k = 0; k < size; k++) {
				try {
					Map map = (Map) data.get(k);
					String customerId = (String) map.get("CUSTOMERID");
					CustomerAttributes customerAttribute = new CustomerAttributes();
					customerAttribute.setCustomerId(customerId);

					customerAttribute.setState((String) map.get("STATE"));
					map.remove("STATE");

					String signatureTemp = (String) map.get("SIGNATURE");
					if(signatureTemp == null || signatureTemp.trim().equals("")) signatureTemp = "0";
					int signature = 0;
					try {
						signature = Integer.parseInt(signatureTemp);
					} catch (Exception e) {
						signature = 0;
						log.error("导入客户数据-->非法的值-->是否签到(signature)["
								+ signatureTemp + "]");
					}
					customerAttribute.setSignature(signature);
					map.remove("SIGNATURE");

					customerAttribute.setSignTime((String) map.get("SIGNTIME"));
					map.remove("SIGNTIME");

					String amountTemp = (String) map.get("AMOUNT");
					float amount = 0;
					try {
						if(amountTemp != null && !amountTemp.trim().equals("")){
							amount = Float.parseFloat(amountTemp);
						}
					} catch (Exception e) {
						amount = 0;
						log.error("导入客户数据-->非法的值-->支付金额(amount)[" + amountTemp
								+ "]");
					}
					customerAttribute.setAmount(amount);
					map.remove("AMOUNT");

					customerAttribute.setPayTime((String) map.get("PAYTIME"));
					map.remove("PAYTIME");

					String userSno = (String)map.get("USERSNO");
					if(userSno == null || userSno.trim().equals("")){
						userSno = session.getUserName();
					}
					map.put("USERSNO", userSno);
					
					String roleId = (String)map.get("ROLEID");
					if(roleId == null || roleId.trim().equals("")){
						roleId = session.getAccessSno();
					}
					map.put("ROLEID", roleId);
					
					
					Customer customer = customerDAO
							.findCustomerById(customerId);
					int r = -1;
					if (customer == null) {
						String mobile = (String) map.get("MOBILE");
						String customerName = (String) map.get("CUSTOMERNAME");
						customer = customerDAO.findCustomerByMobile(mobile);
						if (customer != null) {
							customer = customerDAO.findCustomerByNameAndMobile(
									customerName, mobile);
							if (customer != null) { // 一个已经存在的客户,修改信息
								map.put("CUSTOMERID", customer.getCustomerId());
								customerAttribute.setCustomerId(customer
										.getCustomerId());
								r = modify(map, customerAttribute);
							} else {// 重复的手机号,不导入信息
								result.append("客户 [" + customerName + "] 的手机号["
										+ mobile + "]重复.</BR>");
								count--;
								continue;
							}
						} else
							r = add(map, customerAttribute);
					} else {
						r = modify(map, customerAttribute);
					}
					if (r < 0)
						count--;
				} catch (Exception e) {
					System.out.println(e);
					count--;
					continue;
				}
			}
		}
		result.append("数据导入成功!</BR>共导入客户" + count + "个.");

		if (excelTool.info != null) {
			result.append(excelTool.info + "</br>");
			excelTool.info = null;
		}
		return result.toString();
	}

	private int add(Map map, CustomerAttributes customerAttribute)
			throws Exception {
		String customerId = CodeFactory.getCostomerCodeBySQL();
		map.put("CUSTOMERID", customerId);
		int r = customerDAO.insert(map);
		if (r > -1) {
			customerAttribute.setCustomerId(customerId);
			r = saveCustomerAttribute(customerAttribute);
		}
		return r;
	}

	private int modify(Map map, CustomerAttributes customerAttribute)
			throws Exception {
		int r = customerDAO.modify(map);
		if (r > -1) {
			r = saveCustomerAttribute(customerAttribute);
		}
		return r;
	}

	private int saveCustomerAttribute(CustomerAttributes customerAttribute) {
		try {
			CustomerAttributes temp = customerAttributesDAO
					.findByCustomerIdAndState(
							customerAttribute.getCustomerId(),
							customerAttribute.getState());
			if (temp == null)
				return customerAttributesDAO.insert(customerAttribute);
			else
				return customerAttributesDAO
						.modifyByCustomerIdAndState(customerAttribute);
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		}
	}

	/**
	 * @author yxwonline.com
	 * @description 导出
	 * @date 2010-8-14 下午09:46:27
	 */
	public String exportOut(String filePath, String url, String customerId,
			String where) throws Exception {
		String result = "";
		int count = 0;
		if (customerId.endsWith(","))
			customerId = customerId.substring(0, customerId.length() - 1);
		List data = customerDAO.findExpordData(customerId, where);
		count = customerDAO.getExportCount(customerId, where);
		result = "共导出客户" + count + "个";

		Map label = new HashMap();
		label.put("CUSTOMERID", "客户编码");
		label.put("CUSTOMERNAME", "客户名称");
		label.put("COMPANYNAME", "公司名称");
		label.put("PROVINCE", "省份");
		label.put("CITY", "城市");
		label.put("PHONE", "电话");
		label.put("MOBILE", "手机");
		label.put("QQ", "QQ");
		label.put("EMAIL", "EMAIL");
		label.put("BIRTHDAY", "出生日期");
		label.put("USERSNO", "服务人员");
		label.put("ROLEID", "查阅角色");
		label.put("MEMO", "备注");

		label.put("STATE", "客户类别");
		label.put("SIGNATURE", "是否已签到(1-是 0-否)");
		label.put("SIGNTIME", "签到时间");
		label.put("AMOUNT", "支付金额(元)");
		label.put("PAYTIME", "支付时间");

		excelTool.setFilePath(filePath);
		excelTool.write(data, label, title, 9);
		result += "</br>导出成功!";
		String fn = new File(filePath).getName();
		result += "</br>点击下载:<a href=\"" + url + fn + "\" alt=\"点击下载\">" + fn
				+ "</a>";

		if (excelTool.info != null) {
			result = excelTool.info + "</br>" + result;
			excelTool.info = null;
		}

		return result;
	}

	/**
	 * 报名信息导出
	 */
	public String exportSOut(String filePath, String url, String id,
			String tableName) throws Exception {

		if ("mmuser".equals(tableName)) {
			return exportTGUserOut(filePath, url, id);
		} else if ("mmorder".equals(tableName)) {
			return exportTGOrderOut(filePath, url, id);
		} else {
			return exportSignup(tableName, filePath, url, id);
		}

	}

	private String exportTGUserOut(String filePath, String url, String id)
			throws Exception {
		String[] stitle = null;
		Map label = new HashMap();
		label.put("USERNAME", "称呼");
		label.put("EMAIL", "电子邮件");
		label.put("QQ", "QQ");
		label.put("MOBILE", "手机");
		label.put("PLATFORM", "平台");
		label.put("ACCOUNT", "账号");
		label.put("EXPANDCODE", "推广代码");
		label.put("TYPE", "类型(0-普通会员 1-高级会员)");
		label.put("CREATETIME", "注册时间");
		label.put("AMOUNT", "是否支付佣金(0-否 1-是)");
		label.put("AMOUNTTOTAL", "应支付金额");
		label.put("AMOUNTTOTALHISTORY", "已支付佣金总计");
		label.put("USERSNO", "服务人员");
		stitle = new String[13];
		stitle[0] = "USERNAME";
		stitle[1] = "EMAIL";
		stitle[2] = "QQ";
		stitle[3] = "MOBILE";
		stitle[4] = "PLATFORM";
		stitle[5] = "ACCOUNT";
		stitle[6] = "EXPANDCODE";
		stitle[7] = "TYPE";
		stitle[8] = "CREATETIME";
		stitle[9] = "AMOUNT";
		stitle[10] = "AMOUNTTOTAL";
		stitle[11] = "AMOUNTTOTALHISTORY";
		stitle[12] = "USERSNO";

		List data = exportDAO.findTGUser(id);

		return exportOutAction(id, filePath, label, stitle, url, 8, data);
	}

	private String exportSignup(String tableName, String filePath, String url,
			String id) throws Exception {
		String[] stitle = null;
		Map label = new HashMap();
		if ("childs".equalsIgnoreCase(tableName)
				|| "signup".equalsIgnoreCase(tableName)
				|| "swdt".equalsIgnoreCase(tableName)
				|| "yyuser".equalsIgnoreCase(tableName)) {
			label.put("NAME", "姓名");
			label.put("PHONE", "电话");
			label.put("EMAIL", "电子邮件");
			label.put("ADDRESS", "地址");
			label.put("CONTENT", "报名理由");
			label.put("BMTIME", "报名时间");
			label.put("ISFLAG", "是否上课(0-未上课 1-已上课)");
			label.put("MEMO", "备注");
			stitle = new String[8];
			stitle[0] = "NAME";
			stitle[1] = "PHONE";
			stitle[2] = "EMAIL";
			stitle[3] = "ADDRESS";
			stitle[4] = "CONTENT";
			stitle[5] = "BMTIME";
			stitle[6] = "ISFLAG";
			stitle[7] = "MEMO";
		} else if ("nac".equalsIgnoreCase(tableName)
				|| "nacpx".equalsIgnoreCase(tableName)) {
			label.put("CUSTNAME", "姓名");
			label.put("MOBILE", "电话");
			label.put("EMAIL", "电子邮件");
			label.put("CITY", "城市");
			label.put("CREATETIME", "报名时间");
			label.put("ISFLAG", "是否上课(0-未上课 1-已上课)");
			label.put("MEMO", "备注");
			stitle = new String[7];
			stitle[0] = "CUSTNAME";
			stitle[1] = "MOBILE";
			stitle[2] = "EMAIL";
			stitle[3] = "CITY";
			stitle[4] = "CREATETIME";
			stitle[5] = "ISFLAG";
			stitle[6] = "MEMO";
		}

		List data = exportDAO.findAllById(id, tableName);

		return exportOutAction(id, filePath, label, stitle, url, 5, data);
	}

	private String exportTGOrderOut(String filePath, String url, String id)
			throws Exception {
		String[] stitle = null;
		Map label = new HashMap();
		label.put("ORDERNUMBER", "订单号");
		label.put("PRODUCTNAME", "产品名称");
		label.put("SUBSCRIBER", "订购人");
		label.put("MOBILE", "电话");
		label.put("ADDRESS", "地址");
		label.put("REFERRAL", "推荐人");
		label.put("AMOUNT", "佣金");
		label.put("STATUS", "订单状态");
		label.put("CREATETIME", "订单时间");
		label.put("MEMO", "备注");
		label.put("USERSNO", "服务人员");
		stitle = new String[11];
		stitle[0] = "ORDERNUMBER";
		stitle[1] = "PRODUCTNAME";
		stitle[2] = "SUBSCRIBER";
		stitle[3] = "MOBILE";
		stitle[4] = "ADDRESS";
		stitle[5] = "REFERRAL";
		stitle[6] = "AMOUNT";
		stitle[7] = "STATUS";
		stitle[8] = "CREATETIME";
		stitle[9] = "MEMO";
		stitle[10] = "USERSNO";

		List data = exportDAO.findTGOrder(id);

		return exportOutAction(id, filePath, label, stitle, url, 8, data);
	}

	private String exportOutAction(String id, String filePath, Map label,
			String[] stitle, String url, int dataIndex, List data)
			throws Exception {
		String result;
		int count = 0;
		if (data != null)
			count = data.size();
		result = "共导出" + count + "条.";

		excelTool.setFilePath(filePath);
		excelTool.write(data, label, stitle, dataIndex);
		result += "</br>导出成功!";
		String fn = new File(filePath).getName();
		result += "</br>点击下载:<a href=\"" + url + fn + "\" alt=\"点击下载\">" + fn
				+ "</a>";

		if (excelTool.info != null) {
			result = excelTool.info + "</br>" + result;
			excelTool.info = null;
		}

		return result;
	}
}